/* Copyright (c) [2024] [ylc]. Licensed under Apache-2.0 License. */
#include "demo.h"
#include "i2cDriveS.h"

sI2CTypedef_t EgsI2c={0};
sI2C_t siic={0};

static void i2c_IoInit(void) {
}

static void i2c_SdaH(void) {
}

static void i2c_SdaL(void) {
}

static unsigned char i2c_ReadSda(void) {
    return 0;
}

static unsigned char i2c_ReadScl(void) {
    return 0;
}

static void i2c_callback(sI2C_CbTypedef_e i2c_CbType)
{
    unsigned char write_addr = 0;
    unsigned char send_addr = 0;
    unsigned char tmp_data;
    switch (i2c_CbType)
    {
        case IIC_S_IT_IDLE: { //空闲         
            siic.tx_index = 0;
            siic.rx_index = 0;
        }break;
		case IIC_S_IT_START: { //起始信号         
            siic.tx_index = 0;
            siic.rx_index = 0;
        }break;
        case IIC_S_IT_RECV: { //接收中断           
            siic.rx_buf[siic.rx_index] = EgsI2c.Value;  //从iic句柄中获取接收到的数据
            siic.rx_index++;
            if (siic.rx_index >= EGS_REG_LEN+2) siic.rx_index = EGS_REG_LEN + 1;	//防溢出

            if (siic.rx_index == 2) {		//接收到操作地址
                siic.addr = siic.rx_buf[1];
                siic.tx_index = 0;
            }
            else if (siic.rx_index > 2) {	//接收写入数据
                write_addr = siic.addr + siic.rx_index - 3;
                if (write_addr >= EGS_REG_LEN) write_addr = EGS_REG_LEN - 1;	//防溢出
                siic.reg[write_addr] = siic.rx_buf[siic.rx_index - 1];		    //写入到参数表  
            }
        }break;
        case IIC_S_IT_SEND: { //发送中断		
            send_addr = siic.addr + siic.tx_index;
            tmp_data = siic.reg[send_addr];
            siic.tx_index = siic.tx_index + 1;
            EgsI2c.Value = tmp_data;                    //将待发数据写入到iic句柄
        }break;
        case IIC_S_IT_PEND: { //主机回UACK
            siic.tx_index = 0;
        }break;
        default:
            break;
    }
}


void egs_i2c_init(sI2CTypedef_t* i2c) {
    i2c->DevAddrSet=EGS_ADDR;
	i2c->IIC_IO_INIT = i2c_IoInit;
	i2c->IIC_SDA_H = i2c_SdaH;
	i2c->IIC_SDA_L = i2c_SdaL;
	i2c->IIC_READ_SDA = i2c_ReadSda;
	i2c->IIC_READ_SCL = i2c_ReadScl;
    i2c->IIC_CALLBACK=i2c_callback;
}

void egs_init(void)
{
    egs_i2c_init(&EgsI2c);
    EgsI2c.IIC_IO_INIT();
}

//扫描io/外部中断
void egs_iic_it(void)
{
    static unsigned char sda = 0;
    static unsigned char scl = 0;
    static unsigned char sda_old = 0;
    static unsigned char scl_old = 0;

    sda = i2c_ReadSda();
    scl = i2c_ReadScl();

    if (sda_old != sda) {
        if (sda == 0) {
            i2c_Sda_L_Cb(&EgsI2c);      //等效sda下降沿中断
        }
        else {
            i2c_Sda_H_Cb(&EgsI2c);      //等效sda上升沿中断
        }
        sda_old = sda;
    }
    if (scl_old != scl) {
        if (scl == 0) {
            i2c_Scl_L_Cb(&EgsI2c);
        }
        else {
            i2c_Scl_H_Cb(&EgsI2c);
        }
        scl_old = scl;
    }
}




